package doctor

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
)

func (b Base) CreatePatient(c *gin.Context, req *CreatePatientRequest) *CreatePatientResponse {
	user := &model.User{
		Username: req.Name,
		Phone:    req.Phone,
	}
	err := user.Create(config.DB)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	detail := &model.UserDetail{}
	detail.UserId = user.ID
	_ = detail.GetByUserId(config.DB)

	updateDetail(req, detail)

	_ = detail.Update(config.DB)

	return &CreatePatientResponse{ID: user.ID}
}

func (b Base) UpdatePatient(c *gin.Context, req *CreatePatientRequest) *struct{} {
	user := &model.User{}
	user.ID = req.ID
	if err := user.Get(config.DB); err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	user.Username = req.Name
	user.Phone = req.Phone

	if err := user.Update(config.DB); err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	detail := &model.UserDetail{}
	detail.UserId = user.ID
	if err := detail.GetByUserId(config.DB); err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	updateDetail(req, detail)

	_ = detail.Update(config.DB)

	return &struct{}{}
}

type CreatePatientRequest struct {
	ID             uint `json:"id"`
	Name           string
	Phone          string
	Gender         int
	Age            int
	Weight         float32
	Height         float32
	Smoke          float32
	Alcohol        int
	Diabetes       float32
	Macro          int
	Micro          int
	Hba1c          float32
	Hypoglycemia   int
	TypeOfDiabetes string
}

type CreatePatientResponse struct {
	ID uint
}

func updateDetail(req *CreatePatientRequest, detail *model.UserDetail) {
	if req.Gender == 1 {
		detail.Gender = 1
	} else {
		detail.Gender = 2
	}

	if req.Age != 0 {
		detail.Age = int8(req.Age)
	}

	if req.Weight != 0 {
		detail.Weight = req.Weight
	}

	if req.Height != 0 {
		detail.Height = req.Height
	}

	if req.Smoke != 0 {
		detail.SmokingHistory = req.Smoke
	}

	if req.Alcohol == 0 {
		detail.AlcoholDrinkingHistory = "non-drinker"
	} else {
		detail.AlcoholDrinkingHistory = "drinker"
	}

	detail.DurationOfDiabetes = req.Diabetes

	if req.Macro == 0 {
		detail.DiabeticMacrovascularComplications = "none"
	} else {
		detail.DiabeticMacrovascularComplications = "have"
	}

	if req.Micro == 0 {
		detail.DiabeticMicrovascularComplications = "none"
	} else {
		detail.DiabeticMicrovascularComplications = "have"
	}

	detail.Hba1c = req.Hba1c

	detail.Hypoglycemia = int8(req.Hypoglycemia)

	detail.TypeOfDiabetes = req.TypeOfDiabetes
}
